# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Rafael Pivato
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Rafael Pivato nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL RAFAEL PIVATO BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import urllib2
from bcoma import BcomaFormatError
from bcoma import create_api_uri
from bcoma import download_json
from bcoma.character import Character


class Guild(object):
    """Represents an existing guild from the Blizzard Community Site."""

    def __init__(self, data=None):
        """Initializes a new instance of a Guild object."""
        if data is None:
            self.achievement_points = 0
            self.last_modified = 0
            self.level = 1
            self.name = 'Unknown'
            self.realm = 'Unknown'
            self.side = 0
            self.members = []
        else:
            try:
                self.achievement_points = data['achievementPoints']
                self.last_modified = data['lastModified']
                self.level = data['level']
                self.name = data['name']
                self.realm = data['realm']
                self.side = data['side']
            except KeyError as missing_key:
                detail = 'Missing Guild JSON key %s.' % (missing_key)
                raise BcomaFormatError('unknown', missing_key, detail)
            else:
                self.members = []
                if 'members' in data:
                    for member_data in data['members']:
                        self.members.append(Member(guild=self,
                                                   data=member_data))

    @classmethod
    def fetch(cls, realm, name, fields=[]):
        """Fetches profile information for the given guild."""
        realm = urllib2.quote(realm)
        name = urllib2.quote(name)
        query = []
        if len(fields) > 0:
            query.append(('fields', ''.join(fields)))
        path = 'guild/%s/%s' % (realm, name)
        uri = create_api_uri(path, query)
        data = download_json(uri)
        if 'status' in data and data['status'] == 'nok':
            return None
        else:
            try:
                return Guild(data=data)
            except BcomaFormatError as format_error:
                format_error.uri = uri
                raise format_error

    def __str__(self):
        name = self.name.encode('ascii', 'replace')
        realm = self.realm.encode('ascii', 'replace')
        return '%s (%s - %d)' % (name, realm, self.level)

    def __unicode__(self):
        return u'%s (%s - %d)' % (self.name, self.realm, self.level)

    @classmethod
    def fetch_members(cls, realm, name):
        """Fetches profile and members information for the given guild."""
        return cls.fetch(realm, name, ['members'])


class Member(object):
    """Represents a member in a guild."""

    def __init__(self, guild=None, data=None):
        """Initializes a new instnace of a Member object."""
        self.guild = guild
        if data is None:
            self.rank = 0
            self.character = None
            self.guild = None
        else:
            try:
                self.rank = data['rank']
                self.character = Character(guild=guild, data=data['character'])
            except KeyError as missing_key:
                detail = 'Missing Member JSON key %s.' % (missing_key)
                raise BcomaFormatError('unknown', missing_key, detail)
